// pages/reviews/reviews.ts
import { MerchantAPI } from '../../utils/api'

const CONTENT_PREVIEW_LENGTH = 120;
const MAX_REPLY_LENGTH = 200;

interface Review {
  reviewId: number;
  orderId: number;
  orderNo?: string;
  customerId: number;
  customerName: string;
  customerAvatar: string;
  score: number;              // 后端返回的评分字段
  rating?: number;            // 前端使用的评分字段（兼容）
  content: string;
  images?: string;            // 后端返回的JSON字符串
  imageList?: string[];       // 后端处理后的图片数组
  isAnonymous: number;        // 0-否，1-是
  createTime: string;
  hasReply?: boolean;         // 前端使用的字段
  replied?: boolean;          // 后端返回的字段
  replyContent?: string;
  repliedAt?: string;        // 后端返回的回复时间
  replyTime?: string;         // 前端使用的回复时间（兼容）
  starStates?: boolean[];     // 星星状态数组，用于显示 [true, true, true, false, false] 表示3星
  previewContent?: string;
  isContentOverflow?: boolean;
  // 以下字段前端可能不需要，但保留以兼容
  tags?: string[];
  productInfo?: {
    productId: number;
    productName: string;
    productImage: string;
  };
}

interface ReviewsPageData {
  hasLogin: boolean;
  loading: boolean;
  refreshing: boolean;
  headerHeight: number;      // 占位元素高度
  navBarHeight: number;       // 导航栏高度（用于动态设置固定头部的top值）
  
  // 统计数据
  statistics: {
    overallRating: number;    // 平均评分
    totalReviews: number;      // 总评价数
    ratingDistribution: Record<string, number>;  // 评分分布（百分比）
    dimensionRatings: {
      productQuality: number;
      service: number;
      delivery: number;
    };
    avgStarStates?: Array<{ filled: boolean; percentage?: number }>;  // 平均评分的星星状态数组，支持部分填充
    // 后端返回的原始数据
    avgScore?: number;
    totalCount?: number;
    repliedCount?: number;
    unRepliedCount?: number;
    goodRate?: number;
    scoreDistribution?: Array<{
      score: number;
      count: number;
      percentage: number;
    }>;
  };
  
  // 评价列表
  reviews: Review[];
  filteredReviews: Review[];
  unrepliedCount: number;
  
  // 筛选
  activeFilter: string;
  
  // 分页
  pageNum: number;             // 当前页码（后端使用pageNum）
  pageSize: number;            // 每页数量（后端使用pageSize）
  total: number;               // 总记录数
  hasMore: boolean;
  
  // 回复功能
  showReplyModal: boolean;
  replyingReview: Review | null;
  replyContent: string;
  replyContentLength: number;
  quickReplies: string[];
  showContentModal: boolean;
  contentModalReview: Review | null;
}

Page({
  data: {
    hasLogin: false,
    loading: false,
    refreshing: false,
    headerHeight: 0,  // 占位元素高度（导航栏高度 + 固定头部高度）
    navBarHeight: 0,  // 导航栏高度（用于动态设置固定头部的top值）
    
    // 统计数据
    statistics: {
      overallRating: 0,
      totalReviews: 0,
      ratingDistribution: {},
      dimensionRatings: {
        productQuality: 0,
        service: 0,
        delivery: 0
      }
    },
    
    // 评价列表
    reviews: [],
    filteredReviews: [],
    unrepliedCount: 0,
    
    // 筛选
    activeFilter: 'all',
    
    // 分页
    pageNum: 1,
    pageSize: 10,
    total: 0,
    hasMore: true,
    
    // 回复功能
    showReplyModal: false,
    replyingReview: null,
    replyContent: '',
    replyContentLength: 0,  // 回复内容长度，用于按钮禁用判断
    quickReplies: [
      '感谢您的评价！',
      '感谢您的光临，您的意见和建议就是对我们最好的支持！',
      '我们会继续努力提供更好的服务',
      '非常抱歉给您带来不便，我们会立即改进',
      '您的满意是我们最大的动力'
    ],
    showContentModal: false,
    contentModalReview: null
  } as ReviewsPageData,

  onLoad() {
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.loadReviewStatistics();
      this.loadReviews();
      // 在数据加载后再计算固定头部高度
      setTimeout(() => {
        this.calculateHeaderHeight();
      }, 300);
    }
  },

  /**
   * 计算固定头部高度
   */
  calculateHeaderHeight() {
    // 使用setTimeout确保DOM已渲染
    setTimeout(() => {
      const query = wx.createSelectorQuery().in(this);
      // 同时获取导航栏和固定头部的高度
      query.select('.weui-navigation-bar__inner').boundingClientRect();
      query.select('.fixed-header').boundingClientRect();
      query.exec((res: any) => {
        const navBarRect = res[0];
        const fixedHeaderRect = res[1];
        
        if (fixedHeaderRect && navBarRect) {
          // 占位高度 = 导航栏高度 + 固定头部高度（因为两者都是fixed定位）
          const navBarHeight = navBarRect.height; // 导航栏高度（包含状态栏）
          const fixedHeaderHeight = fixedHeaderRect.height; // 固定头部内容高度
          // 添加额外的安全边距（30px），确保第一条评论不被遮挡
          const totalHeight = navBarHeight + fixedHeaderHeight + 30;
          
          // 同时动态设置固定头部区域的top值，确保它从导航栏底部开始
          // 将导航栏高度转换为rpx（1px ≈ 2rpx）
          const navBarHeightRpx = navBarHeight * 2;
          
          console.log('计算头部高度:', {
            navBarHeight,
            fixedHeaderHeight,
            totalHeight,
            navBarHeightRpx
          });
          
          this.setData({
            headerHeight: totalHeight,
            navBarHeight: navBarHeight // 保存导航栏高度，用于动态设置固定头部的top值
          });
          
          // 动态设置固定头部区域的top值
          const query2 = wx.createSelectorQuery().in(this);
          query2.select('.fixed-header').fields({
            computedStyle: ['top']
          });
          query2.exec(() => {
            // 通过内联样式设置top值
            const fixedHeaderQuery = wx.createSelectorQuery().in(this);
            fixedHeaderQuery.select('.fixed-header').boundingClientRect();
            fixedHeaderQuery.exec(() => {
              // top值已经在CSS中设置，这里只需要确保占位元素高度正确
            });
          });
        } else {
          // 如果获取失败，使用估算值
          try {
            const systemInfo = wx.getSystemInfoSync();
            const safeAreaTop = (systemInfo.safeArea && (systemInfo.safeArea as any).top) || 0;
            const navBarContentHeight = 48; // 使用48px确保兼容Android
            const navBarHeight = safeAreaTop + navBarContentHeight; // 导航栏总高度
            // 统计区域约 400rpx ≈ 200px + 筛选区域约 100rpx ≈ 50px + padding 40rpx ≈ 20px
            const fixedHeaderHeight = 200 + 50 + 20; // 固定头部内容高度（转换为px）
            // 添加额外的安全边距（30px），确保第一条评论不被遮挡
            const totalHeight = navBarHeight + fixedHeaderHeight + 30;
            
            console.log('使用估算高度:', {
              safeAreaTop,
              navBarHeight,
              fixedHeaderHeight,
              totalHeight
            });
            
            this.setData({
              headerHeight: totalHeight,
              navBarHeight: navBarHeight
            });
          } catch (e) {
            // 如果获取系统信息失败，使用默认值
            this.setData({
              headerHeight: 600, // 默认高度600px
              navBarHeight: 100 // 默认导航栏高度100px
            });
          }
        }
      });
    }, 200); // 增加延迟时间，确保DOM完全渲染
  },

  onShow() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 去登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  /**
   * 计算维度评分（基于评价内容关键词）
   */
  calculateDimensionRatings(reviews: Review[]) {
    // 定义关键词
    const productQualityKeywords = [
      '质量', '品质', '新鲜', '好吃', '味道', '口感', '食材', '菜品', 
      '美味', '难吃', '变质', '不新鲜', '质量差', '品质差', '味道差'
    ];
    const serviceKeywords = [
      '服务', '态度', '客服', '热情', '耐心', '专业', '周到', '贴心',
      '服务差', '态度差', '不热情', '不耐烦', '服务态度', '客服态度'
    ];
    const deliveryKeywords = [
      '配送', '送达', '速度', '快', '慢', '及时', '准时', '延迟',
      '配送快', '配送慢', '送餐', '物流', '快递', '送达时间'
    ];
    
    let productQualitySum = 0;
    let productQualityCount = 0;
    let serviceSum = 0;
    let serviceCount = 0;
    let deliverySum = 0;
    let deliveryCount = 0;
    
    reviews.forEach(review => {
      const content = review.content || '';
      const score = review.score || 0;
      
      // 检查商品质量相关关键词
      const hasProductQuality = productQualityKeywords.some(keyword => 
        content.includes(keyword)
      );
      if (hasProductQuality) {
        productQualitySum += score;
        productQualityCount++;
      }
      
      // 检查服务态度相关关键词
      const hasService = serviceKeywords.some(keyword => 
        content.includes(keyword)
      );
      if (hasService) {
        serviceSum += score;
        serviceCount++;
      }
      
      // 检查配送速度相关关键词
      const hasDelivery = deliveryKeywords.some(keyword => 
        content.includes(keyword)
      );
      if (hasDelivery) {
        deliverySum += score;
        deliveryCount++;
      }
    });
    
    return {
      // 四舍五入到整数
      productQuality: productQualityCount > 0 ? Math.round(productQualitySum / productQualityCount) : 0,
      service: serviceCount > 0 ? Math.round(serviceSum / serviceCount) : 0,
      delivery: deliveryCount > 0 ? Math.round(deliverySum / deliveryCount) : 0
    };
  },

  /**
   * 加载评价统计
   */
  async loadReviewStatistics() {
    try {
      const response = await MerchantAPI.getReviewStatistics();
      
      if (response && response.code === 200 && response.data) {
        const data = response.data;
        
        // 转换评分分布数据
        const ratingDistribution: Record<string, number> = {};
        if (data.scoreDistribution && Array.isArray(data.scoreDistribution)) {
          data.scoreDistribution.forEach((item: any) => {
            ratingDistribution[item.score] = item.percentage || 0;
          });
        }
        
        // 填充缺失的评分（确保1-5星都有值）
        for (let i = 1; i <= 5; i++) {
          if (!ratingDistribution[i]) {
            ratingDistribution[i] = 0;
          }
        }
        
        // 生成平均评分的星星状态数组（支持小数部分）
        const avgRating = data.avgScore || 0;
        const avgStarStates: Array<{ filled: boolean; percentage?: number }> = [];
        for (let i = 0; i < 5; i++) {
          const starIndex = i + 1; // 第几颗星（1-5）
          if (starIndex <= Math.floor(avgRating)) {
            // 完全填充的星星
            avgStarStates.push({ filled: true });
          } else if (starIndex === Math.floor(avgRating) + 1) {
            // 部分填充的星星（小数部分）
            const decimalPart = avgRating - Math.floor(avgRating);
            if (decimalPart > 0) {
              avgStarStates.push({ filled: false, percentage: decimalPart * 100 });
            } else {
              avgStarStates.push({ filled: false });
            }
          } else {
            // 未填充的星星
            avgStarStates.push({ filled: false });
          }
        }
        
        // 初始化维度评分（如果还没有评价列表，则设为0，后续会在加载评价后更新）
        const dimensionRatings = this.data.reviews && this.data.reviews.length > 0
          ? this.calculateDimensionRatings(this.data.reviews)
          : { productQuality: 0, service: 0, delivery: 0 };
        
        this.setData({
          statistics: {
            overallRating: avgRating,
            totalReviews: data.totalCount || 0,
            ratingDistribution: ratingDistribution,
            dimensionRatings: dimensionRatings,
            // 保留后端原始数据
            avgScore: data.avgScore,
            totalCount: data.totalCount,
            repliedCount: data.repliedCount,
            unRepliedCount: data.unRepliedCount,
            goodRate: data.goodRate,
            scoreDistribution: data.scoreDistribution,
            avgStarStates: avgStarStates  // 平均评分的星星状态数组
          },
          unrepliedCount: data.unRepliedCount || 0
        });
        
        // 重新计算固定头部高度（因为统计区域内容可能变化）
        setTimeout(() => {
          this.calculateHeaderHeight();
        }, 100);
      }
      
    } catch (error) {
      console.error('加载评价统计失败:', error);
      wx.showToast({
        title: '加载统计失败',
        icon: 'none'
      });
    }
  },

  /**
   * 加载评价列表
   */
  async loadReviews(isRefresh = false) {
    // 确定当前页码
    let currentPageNum = this.data.pageNum;
    if (isRefresh) {
      currentPageNum = 1;
      this.setData({
        pageNum: 1,
        reviews: [],
        hasMore: true
      });
    }

    this.setData({ 
      loading: true,
      refreshing: isRefresh 
    });

    try {
      // 构建查询参数
      const params: any = {
        pageNum: currentPageNum,
        pageSize: this.data.pageSize
      };
      
      // 根据筛选条件添加参数
      switch (this.data.activeFilter) {
        case 'unreplied':
          params.repliedFilter = false;  // 未回复
          break;
        case 'favorable':
          // 好评：4-5星，这里需要分别查询，或者前端筛选
          // 由于后端只支持单个score筛选，这里先不传score，前端再筛选
          break;
        case 'critical':
          // 差评：1-2星，同样需要前端筛选
          break;
        default:
          // 全部，不传筛选参数
          break;
      }
      
      const response = await MerchantAPI.getReviews(params);
      
      if (response && response.code === 200) {
        // 若依框架的TableDataInfo返回格式：{code, msg, rows, total}
        const list = response.rows || response.data?.rows || response.data?.list || [];
        const total = response.total || response.data?.total || 0;
        
        // 转换数据格式
        const reviews: Review[] = list.map((item: any) => {
          const score = Number(item.score) || 0;
          const content = item.content || '';
          const isContentOverflow = content.length > CONTENT_PREVIEW_LENGTH;
          // 生成星星状态数组：5颗星，前score颗为true（亮的），后面的为false（灰的）
          const starStates: boolean[] = [];
          for (let i = 0; i < 5; i++) {
            starStates.push(i < score);
          }
          
          const review: Review = {
            reviewId: item.reviewId,
            orderId: item.orderId,
            orderNo: item.orderNo,
            customerId: item.customerId,
            customerName: item.customerName || (item.isAnonymous === 1 ? '匿名用户' : '用户'),
            customerAvatar: item.customerAvatar || '/images/default-avatar.png',
            score: score,
            rating: score,  // 兼容前端使用的rating字段，确保是数字类型
            content: item.content || '',
            images: item.images,
            imageList: item.imageList || [],
            isAnonymous: item.isAnonymous || 0,
            createTime: item.createTime || '',
            hasReply: item.replied || false,
            replied: item.replied || false,
            replyContent: item.replyContent,
            repliedAt: item.repliedAt,
            replyTime: item.repliedAt,  // 兼容前端使用的replyTime字段
            starStates: starStates,  // 星星状态数组
            previewContent: isContentOverflow ? content.slice(0, CONTENT_PREVIEW_LENGTH) : content,
            isContentOverflow
          };
          return review;
        });
        
        const mergedReviews = isRefresh ? reviews : [...this.data.reviews, ...reviews];
        const hasMore = mergedReviews.length < total;
        const updates: Partial<ReviewsPageData> & { reviews: Review[] } = {
          reviews: mergedReviews,
          total: total,
          hasMore: hasMore,
          pageNum: reviews.length > 0 ? currentPageNum + 1 : currentPageNum
        };
        
        this.setData(updates, () => {
          this.filterReviewList();
          const dimensionRatings = this.calculateDimensionRatings(this.data.reviews);
          this.setData({
            'statistics.dimensionRatings': dimensionRatings
          });
          this.calculateHeaderHeight();
        });

      } else {
        throw new Error(response?.msg || '获取评价列表失败');
      }

    } catch (error: any) {
      console.error('加载评价列表失败:', error);
      wx.showToast({
        title: error?.msg || '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  /**
   * 筛选评价列表
   */
  filterReviewList() {
    let filtered = this.data.reviews;
    
    // 注意：由于后端接口的限制，好评和差评的筛选已经在loadReviews中处理
    // 这里只需要处理未回复的筛选（如果后端没有传repliedFilter参数）
    switch (this.data.activeFilter) {
      case 'unreplied':
        filtered = filtered.filter(review => !review.hasReply && !review.replied);
        break;
      case 'favorable':
        // 已经在loadReviews中筛选了4-5星
        filtered = filtered.filter(review => review.score >= 4);
        break;
      case 'critical':
        // 已经在loadReviews中筛选了1-2星
        filtered = filtered.filter(review => review.score <= 2);
        break;
      default:
        // 显示全部
        break;
    }
    
    this.setData({
      filteredReviews: filtered
    });
  },

  /**
   * 筛选评价
   */
  filterReviews(e: any) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      activeFilter: filter
    });
    // 切换筛选条件时重新加载数据
    this.loadReviews(true);
  },

  /**
   * 回复评价
   */
  replyToReview(e: any) {
    console.log('回复评价按钮被点击', e);
    
    const reviewId = e.currentTarget?.dataset?.reviewId;
    console.log('获取到的评价ID:', reviewId);
    
    if (!reviewId) {
      console.error('回复评价失败：未获取到评价ID', e);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
      return;
    }
    
    // 从列表中查找对应的评价
    const review = this.data.reviews.find(r => r.reviewId === reviewId) || 
                   this.data.filteredReviews.find(r => r.reviewId === reviewId);
    
    console.log('查找到的评价:', review);
    
    if (!review) {
      console.error('回复评价失败：未找到对应的评价信息', {
        reviewId,
        reviewsCount: this.data.reviews.length,
        filteredReviewsCount: this.data.filteredReviews.length
      });
      wx.showToast({
        title: '评价信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否已回复
    if (review.hasReply || review.replied) {
      wx.showToast({
        title: '该评价已回复',
        icon: 'none'
      });
      return;
    }
    
    // 确保replyingReview有starStates
    const replyingReviewWithStars = {
      ...review,
      starStates: review.starStates || (() => {
        const score = review.score || review.rating || 0;
        const states: boolean[] = [];
        for (let i = 0; i < 5; i++) {
          states.push(i < score);
        }
        return states;
      })()
    };
    
    console.log('打开回复弹窗，评价信息:', replyingReviewWithStars);
    this.setData({
      showReplyModal: true,
      replyingReview: replyingReviewWithStars,
      replyContent: '',
      replyContentLength: 0
    });
  },

  /**
   * 提交回复
   */
  async submitReply() {
    console.log('提交回复按钮被点击');
    const { replyingReview, replyContent } = this.data;
    
    console.log('当前数据:', {
      replyingReview: replyingReview ? { reviewId: replyingReview.reviewId } : null,
      replyContent: replyContent,
      replyContentLength: replyContent ? replyContent.length : 0,
      replyContentTrimmed: replyContent ? replyContent.trim() : '',
      replyContentTrimmedLength: replyContent ? replyContent.trim().length : 0
    });
    
    if (!replyingReview) {
      console.error('提交回复失败：评价信息不存在');
      wx.showToast({
        title: '评价信息错误',
        icon: 'none'
      });
      return;
    }
    
    if (!replyContent || !replyContent.trim()) {
      console.warn('提交回复失败：回复内容为空', { replyContent });
      wx.showToast({
        title: '请输入回复内容',
        icon: 'none'
      });
      return;
    }

    console.log('开始提交回复，评价ID:', replyingReview.reviewId, '回复内容:', replyContent.trim());
    this.setData({ loading: true });

    try {
      // 调用后端API
      const response = await MerchantAPI.replyToReview({
        reviewId: replyingReview.reviewId,
        replyContent: replyContent.trim()
      });

      if (response && response.code === 200) {
        // 更新本地数据
        const updatedReviews = this.data.reviews.map(review => {
          if (review.reviewId === replyingReview.reviewId) {
            const now = new Date();
            const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
            return {
              ...review,
              hasReply: true,
              replied: true,
              replyContent: replyContent.trim(),
              repliedAt: timeStr,
              replyTime: timeStr
            };
          }
          return review;
        });

        this.setData({
          reviews: updatedReviews,
          showReplyModal: false,
          replyContent: '',
          replyContentLength: 0,
          unrepliedCount: Math.max(0, this.data.unrepliedCount - 1)
        });

        this.filterReviewList();
        this.loadReviewStatistics();

        wx.showToast({
          title: '回复成功',
          icon: 'success'
        });
      } else {
        throw new Error(response?.msg || '回复失败');
      }

    } catch (error: any) {
      console.error('回复评价失败:', error);
      wx.showToast({
        title: error?.msg || '回复失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 选择快捷回复
   */
  selectQuickReply(e: any) {
    let content = e.currentTarget.dataset.content || '';
    if (content.length > MAX_REPLY_LENGTH) {
      content = content.slice(0, MAX_REPLY_LENGTH);
      wx.showToast({
        title: `最多输入${MAX_REPLY_LENGTH}字`,
        icon: 'none'
      });
    }
    this.setData({
      replyContent: content,
      replyContentLength: content.trim().length
    });
  },

  /**
   * 预览图片
   */
  previewImage(e: any) {
    const urls = e.currentTarget.dataset.urls;
    const current = e.currentTarget.dataset.current;
    
    wx.previewImage({
      urls: urls,
      current: current
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.loadReviewStatistics();
    this.loadReviews(true);
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadReviews(false);
    }
  },

  // 表单输入处理
  onReplyInput(e: any) {
    let value = e.detail.value || '';
    if (value.length > MAX_REPLY_LENGTH) {
      value = value.slice(0, MAX_REPLY_LENGTH);
      wx.showToast({
        title: `最多输入${MAX_REPLY_LENGTH}字`,
        icon: 'none'
      });
    }
    this.setData({
      replyContent: value,
      replyContentLength: value.trim().length
    });
  },

  openReviewDetail(e: any) {
    const reviewId = e.currentTarget.dataset.reviewId;
    if (!reviewId) return;
    const review = this.data.reviews.find(r => r.reviewId === reviewId);
    if (!review) return;
    this.setData({
      showContentModal: true,
      contentModalReview: review
    });
  },

  closeContentModal() {
    this.setData({
      showContentModal: false,
      contentModalReview: null
    });
  },

  // 弹窗控制
  closeReplyModal() {
    this.setData({
      showReplyModal: false,
      replyContent: '',
      replyContentLength: 0
    });
  },

  preventClose() {
    // 阻止事件冒泡
  }
});

